package com.xiaofu.interceptor;

import com.xiaofu.enums.BizCodeEnum;
import com.xiaofu.model.LoginUser;
import com.xiaofu.utils.CommonUtil;
import com.xiaofu.utils.JWTUtil;
import com.xiaofu.utils.JsonData;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("token");
        if (accessToken == null) {
            accessToken = request.getParameter("token");
        }

        if (StringUtils.isNotBlank(accessToken)) {
            // 不为空
            Claims claims = JWTUtil.checkToken(accessToken);
            if (claims == null) {
                // 未登录
                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
                return false;
            }
            Long userId = Long.parseLong(claims.get("id").toString());
            String headImg = claims.get("head_img").toString();
            String name = claims.get("name").toString();
            String mail = claims.get("mail").toString();

            LoginUser loginUser = LoginUser.builder().headImg(headImg).name(name).id(userId).mail(mail).build();
            /*loginUser.setId(userId);
            loginUser.setHeadImg(headImg);
            loginUser.setName(name);
            loginUser.setMail(mail);*/
//            request.setAttribute("loginUser",loginUser);
            threadLocal.set(loginUser);
            return true;
        }

        // 未登录
        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
